#include <iostream>

#include <thrift/Thrift.h>
// #include <thrift/protocol/TProtocol.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TBufferTransports.h>

#include "MessageHistoryService_types.h"
#include "MessageHistoryService.h"
#include "redis_executor/redis_executor.h"
#include "redis_executor/scoped_reply.h"
#include "redis_executor/simple_redis_locator.h"

using namespace std;
using namespace boost;
using namespace apache::thrift;

int main() {
  RedisExecutor redis_(new FixedLocator("127.0.0.1"));
  int count = 1000000;
  const int MAX_BUF = 64;
  char buffer[MAX_BUF] = {0};
  while (count-- > 0) {
    {
      shared_ptr<transport::TTransport> transport(new transport::TMemoryBuffer(16));
      shared_ptr<protocol::TProtocol> protocol(new protocol::TBinaryProtocol(transport));

      imserver::ImMessage item;
      item.__set_seq_id(100);
      item.__set_flags(0);
      item.__set_sender(107);
      item.__set_receiver(403201989);
      item.__set_timestamp(time(NULL));
      item.__set_body("技术是有趣的，做快乐的事情，挣钱何必那么多呢？");

      item.write(protocol.get());

      uint8_t * serialized;
      uint32_t size;
      (dynamic_cast<transport::TMemoryBuffer*>(transport.get()))->getBuffer(&serialized, &size);
      cout << "buf size : "<< size << endl;

      // std::string s = (dynamic_cast<transport::TMemoryBuffer*>(transport.get()))->getBufferAsString();
      std::string s = (dynamic_cast<transport::TMemoryBuffer*>(transport.get()))->getBufferAsString();
      cout << "buf size : "<< s.size() << endl;
      snprintf(buffer, (MAX_BUF - 1), "RPUSH im.test:msg:%ld %%b",  item.receiver);
      ScopedReply reply(redis_.Execute("", buffer, serialized, size));
    }

    {
      snprintf(buffer, (MAX_BUF - 1), "LRANGE im.test:msg:%ld %d %d", 403201989, -20, -1);
      ScopedReply reply(redis_.Execute("", buffer));
      for (size_t i=0; i<reply->elements; ++i) {
        redisReply *elem = reply->element[i];
        shared_ptr<transport::TTransport> transport(new transport::TMemoryBuffer((uint8_t*)elem->str, elem->len));
        shared_ptr<protocol::TProtocol> protocol(new protocol::TBinaryProtocol(transport));
        imserver::ImMessage item2;

        item2.read(protocol.get());
        cout << item2.seq_id << endl;
        cout << item2.sender << endl;
        cout << item2.body << endl;
      }
    }
  }
  return 0;
}
